/*
 * @Description: 
 * @Version: 
 * @Autor: tangwc
 * @Date: 2023-07-02 15:30:02
 * @LastEditors: tangwc
 * @LastEditTime: 2023-07-02 15:45:07
 * @FilePath: \MDK-ARMc:\Git_repository\stm32-demo\stm32_rtos_shell_demo\Core\shell_src\shell_port.c
 * 
 *  Copyright (c) 2023 by tangwc, All Rights Reserved. 
 */
/**
 * @file shell_port.c
 * @author Letter (NevermindZZT@gmail.com)
 * @brief 
 * @version 0.1
 * @date 2019-02-22
 * 
 * @copyright (c) 2019 Letter
 * 
 */
/* Include files -------------------------------------------------------------*/
#include "shell.h"
#include "usart.h"
#include "shell_port.h"

/* Private macro -------------------------------------------------------------*/
#define SHELL_BUFFER_SIZE 512

/* 创建shell对象 */
Shell shell;
/* 开辟shell缓冲区 */
static char shell_buffer[SHELL_BUFFER_SIZE];
static uint8_t rx_buffer = 0;
static uint8_t g_uart_rec_lock = 0;

/* Private function implementation ------------------------------------------*/

/**
 * @brief 用户shell写
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际写入的数据长度
 */
signed short User_Shell_Write(char *data, unsigned short len)
{
    HAL_UART_Transmit(&huart1, (uint8_t *)data, (uint16_t)len, 1000);
    return len;
}


/**
 * @brief 用户shell读
 * 
 * @param data 数据
 * @param len 数据长度
 * 
 * @return short 实际读取到
 */
signed short User_Shell_Read(char *data, unsigned short len)
{
    if(g_uart_rec_lock > 0) {
        g_uart_rec_lock = 0;
        *data = rx_buffer;
        return len;
    }
    return 0;
}

/**
 * @brief 用户shell初始化
 * 
 */
void User_Shell_Init(void)
{
    shell.write = User_Shell_Write;
    shell.read = User_Shell_Read;
    
    /* 开启中断 */
    HAL_UART_Receive_IT(&huart1, &rx_buffer, 1);

    shellInit(&shell, shell_buffer, SHELL_BUFFER_SIZE);
}


/**
 * @description: 串口接收中断回调，接收shell交互数据
 * @return {*}
 * @param {UART_HandleTypeDef} *huart 串口
 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(huart->Instance == USART1)
    {
        g_uart_rec_lock++;
        /* 开启中断 */
        HAL_UART_Receive_IT(&huart1, &rx_buffer, 1);
    }
}
